#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int fd = 0;
    //复制文件描述符1，新分配fd_dup0来标识标准输出
    int fd_dup0 = dup(1);
    printf("fd_dup0 = %d\n",fd_dup0);
    if((fd = open("file1.txt",O_RDWR|O_CREAT|O_TRUNC,0664)) == -1)
    {
        perror("fail to open");
        exit(-1);
    }
    //关闭标准输出后，新分配给fd_dup1的文件描述符1，将会重新标识fd文件描述符所标识的文件
    //此时printf对文件描述符1的操作，实质是对fd的操作
    close(1);
    int fd_dup1 = dup(fd);
    printf("fd_dup1 = %d\n",fd_dup1);
    printf("hello world\n");

    //因为fd_dup0标识的是标准输出，所以先关闭文件描述符1后，新分配给fd_dup1的文件描述符1将会重新标识标准输出
    //此时printf对文件描述符1的操作，实质是就是对标准输出的操作
    close(1);
    int fd_dup2 = dup(fd_dup0);
    printf("fd_dup2 = %d\n",fd_dup2);
    printf("hello world\n");
    return 0;
}